import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Card, Form, Button, Input, Select, Table, Row, message } from "antd";
import { SearchOutlined } from "@ant-design/icons";
//api请求函数
import {
  getHosListRequest,
  getProvinceRequest,
  getCityListRequest,
  getCountyRequest,
  getChangestatusRequest,
} from "@api/hospital/hospitalList";
//类型
import {
  getHosListSearchParamsType,
  hospitalListContentType,
  hospitalListItemsType,
  ProvinceType,
} from "@api/hospital/model/hospitalList";

export default function HospitalList() {
  const Navigate = useNavigate();
  //form实例
  const [form] = Form.useForm();
  //isLoading
  const [isLoading, setIsLoading] = useState(false);
  //page分页初始值
  const [page, setPage] = useState(1);
  //每页条数
  const [limit, setLimit] = useState(3);
  //总条数
  const [totalElements, setTotalElements] = useState(0);
  //搜索框初始值
  const [searchParams, setsearchParams] = useState<getHosListSearchParamsType>(
    {}
  );
  //定义医院列表数据
  const [hospitalList, setHospitalList] = useState<hospitalListContentType>([]);
  //设置省份初始值
  const [province, setProvince] = useState<ProvinceType>([]);
  //设置市区初始值
  const [cityList, setCityList] = useState<ProvinceType>([]);
  //设置县初始值
  const [county, setCounty] = useState<ProvinceType>([]);
  //设置医院类型初始状态
  const [hosType, setHosType] = useState<ProvinceType>([]);
  //设置一个页面重新渲染的状态
  const [reRender, setReRender] = useState(true);
  //初始化前请求列表数据
  useEffect(() => {
    //isLoading
    setIsLoading(true);
    const searchHosList = async () => {
      //获取到请求回来的数据
      const result = await getHosListRequest(page, limit, searchParams);
      //数据列表
      setHospitalList(result.content);
      //总数据长度
      setTotalElements(result.totalElements);
      //isLoading
      setIsLoading(false);
    };
    searchHosList();
  }, [page, limit, searchParams, reRender]);
  //初始化前请求省份
  useEffect(() => {
    const getProvince = async () => {
      const value = await getProvinceRequest();
      setProvince(value);
    };
    getProvince();
  }, []);
  //初始化时请求医院类型
  useEffect(() => {
    const getHosType = async () => {
      const Typevalue = await getCityListRequest("10000");
      setHosType(Typevalue);
    };
    getHosType();
  }, []);
  //
  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      //render的时候 如果有写dataIndex 那么render的参数就是dataIndex的值，如果没有写 则是整个数据
      render(logoData: string) {
        return (
          <img width={120} src={`data:image/jpeg;base64,${logoData}`} alt="" />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(data: hospitalListItemsType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(data: hospitalListItemsType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(status: number) {
        return status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 100,
      fixed: "right" as "right",
      //dataIndex: "id",
      render(data: hospitalListItemsType) {
        return (
          <div>
            <Button type="primary" onClick={jumpHosShow(data.id)}>
              查看
            </Button>
            <Button type="primary" onClick={jumpHosSechedule(data.hoscode)}>
              排班
            </Button>
            <Button
              type="primary"
              // 事件中传递status的值 如果等于0则证明为下线状态 则向后台传递1为上线状态 目的修改后台
              onClick={changeStatus(data.id, data.status === 0 ? 1 : 0)}
            >
              {/* 根据status的状态 如果为0则上线 状态为下线  反之相反*/}
              {data.status === 0 ? "上线" : "下线"}
            </Button>
          </div>
        );
      },
    },
  ];
  //点击分页事件函数
  const clickCurrentHandle = (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
  };
  //通过省份获取市区事件
  const getCityList = async (value: string) => {
    const cityValue = await getCityListRequest(value);
    //设置城市初始状态
    setCityList(cityValue);
    //当我改变省的时候清空市区县
    form.setFieldsValue({ cityCode: null, districtCode: null });
    //清空县的数据
    setCounty([]);
  };
  //通过市区获取县事件
  const getCounty = async (value: string) => {
    const countyValue = await getCountyRequest(value);
    setCounty(countyValue);
    //当改变市区的时候清空掉原有的县
    form.setFieldsValue({ county: null });
  };
  //搜索查询事件
  const searchParamsHandle = (value: getHosListSearchParamsType) => {
    //拿到表单收集的数据传递给state
    setsearchParams(value);
  };
  //清空搜索查询事件
  const resetSearchHandle = () => {
    //设置搜索表单的值为空对象
    setsearchParams({});
  };
  //跳转医院展示事件
  const jumpHosShow = (id: string) => {
    return () => {
      Navigate(`/syt/hospital/hospitallist/hospitalShow/${id}`);
    };
  };
  //跳转医院排班事件
  const jumpHosSechedule = (hoscode: string) => {
    return () => {
      Navigate(`/syt/hospital/hospitallist/HospitalSchedule/${hoscode}`);
    };
  };
  //点击上线下线事件
  const changeStatus = (id: string, status: 0 | 1) => {
    return async () => {
      await getChangestatusRequest(id, status);
      message.success("状态修改成功");
      //重现渲染
      setReRender(!reRender);
    };
  };
  return (
    <div>
      <Card>
        <Form
          onFinish={searchParamsHandle}
          form={form}
          name="basic"
          layout="inline"
          //关闭历史
          autoComplete="off"
        >
          <Row justify="start">
            <Form.Item name="provinceCode" style={{ width: 200 }}>
              <Select
                placeholder="请输入省份"
                allowClear
                onChange={getCityList}
              >
                {province.map((item) => {
                  return (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="cityCode" style={{ width: 200 }}>
              <Select placeholder="请输入市" allowClear onChange={getCounty}>
                {cityList.map((item) => {
                  return (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="districtCode" style={{ width: 200 }}>
              <Select placeholder="请输入县/区" allowClear>
                {county.map((item) => {
                  return (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="hosname" style={{ width: 150 }}>
              <Input placeholder="医院名称" />
            </Form.Item>

            <Form.Item name="hoscode" style={{ width: 150 }}>
              <Input placeholder="医院编号" />
            </Form.Item>
            <Form.Item name="hostype">
              <Select placeholder="医院类型" allowClear>
                {hosType.map((item) => {
                  return (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              name="status"
              //style={{ width: 200, marginTop: "20px" }}
            >
              <Select placeholder="医院状态" allowClear>
                <Select.Option value={1}>上线</Select.Option>
                <Select.Option value={0}>下线</Select.Option>
              </Select>
            </Form.Item>
          </Row>
          <Row justify="start">
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button
                type="primary"
                htmlType="submit"
                style={{ marginTop: "20px" }}
                icon={<SearchOutlined />}
              >
                查询
              </Button>
            </Form.Item>
            <Form.Item
              wrapperCol={{ offset: 8, span: 16 }}
              style={{ marginTop: "20px" }}
            >
              <Button
                type="default"
                htmlType="reset"
                onClick={resetSearchHandle}
              >
                清空
              </Button>
            </Form.Item>
          </Row>
        </Form>
        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          //x轴滚动条
          scroll={{ x: 1500 }}
          //边框
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total: totalElements,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 5, 10],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`;
            },
            //分页事件
            onChange: clickCurrentHandle,
          }}
        />
      </Card>
    </div>
  );
}
